<template>
  <div v-loading="loading">
    <el-page-header class="dep-page-head" @back="$router.back()" title="部门视图">
      <template #content>
        <span style="font-weight: 600;">{{ profileData.name }}</span>
      </template>
      <template #extra>
        <el-button v-if="DeletingDepartmentPermissions" type="danger" plain
          @click="openDeleteDepartmentConfirmMessageBox">
          <el-icon>
            <Delete />
          </el-icon>
        </el-button>
      </template>
    </el-page-header>
    <main>
      <!-- 部门介绍 -->
      <section class="info-container">
        <el-descriptions class="descriptions-list" size="large" border>
          <template #title>
            <div class="descriptions-title">
              <el-icon class="descriptions-title-icon">
                <Cpu />
              </el-icon>
              <span>简介</span>
            </div>
          </template>
          <template #extra>
            <el-button @click="openEditDepDetailDialog" v-if="ModifyingDepartmentInformation">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
          </template>
        </el-descriptions>
        <div v-html="departmentDetail" class="project-introduction"></div>
      </section>
      <!-- 部门身份 -->
      <!-- <section class="info-container">
      <el-descriptions class="descriptions-list" size="large" border>
        <template #title>
          <div class="descriptions-title">
            <el-icon class="descriptions-title-icon">
              <User />
            </el-icon>
            <span>部门身份</span>
          </div>
        </template>
      </el-descriptions>
      <el-table :data="roleList" border>
        <el-table-column prop="id" label="ID">
        </el-table-column>
        <el-table-column prop="name" label="部门身份">
        </el-table-column>
        <el-table-column v-for="permission in permissionsList" :key="permission.id">
          <template #header>
            <el-tooltip class="box-item" effect="dark" placement="top" :content="permission.detail">{{ permission.name
            }}</el-tooltip>
          </template>
          <template #default="scope">
            <span>{{ scope.row.permissions.indexOf(permission.id) > -1 ? 'YES' : '' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </section> -->
      <!-- 部门成员 -->
      <section class="info-container">
        <el-descriptions class="descriptions-list" size="large" border>
          <template #title>
            <div class="descriptions-title">
              <el-icon class="descriptions-title-icon">
                <User />
              </el-icon>
              <span>部门成员</span>
            </div>
          </template>
          <template #extra v-if="ModifyDepartmentMembers">
            <el-button @click="toggleAddMemberInterface">
              <el-icon>
                <Plus />
              </el-icon>
            </el-button>
            <el-button @click="toggleMemberTableEdit">
              <el-icon v-if="memberTableEditEndable">
                <Check />
              </el-icon>
              <el-icon v-else>
                <Edit />
              </el-icon>
            </el-button>
          </template>
        </el-descriptions>
        <el-table :data="profileData.members" border>
          <el-table-column prop="id" label="ID">
            <template v-slot="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="姓名">
            <template v-slot="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="部门身份">
            <template #default="scope">
              <el-select v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.role.id">
                <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value=role.id />
              </el-select>
              <span v-else>{{ scope.row.role.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="annotation" label="备注">
            <template v-slot="scope">
              <el-input v-if="scope.row.inTableEdit != undefined" v-model="scope.row.inTableEdit.annotation"></el-input>
              <span v-else>{{ scope.row.annotation }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="memberTableEditEndable">
            <template v-slot="scope">
              <el-button type="primary" circle @click="toggleInMemberTableEdit(scope.row)">
                <el-icon v-if="scope.row.inTableEdit == undefined">
                  <Edit />
                </el-icon>
                <el-icon v-else>
                  <Check />
                </el-icon>
              </el-button>
              <el-button type="danger" circle @click="openDeleteUserConfirmMessageBox(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-technology-box" v-if="addMemberBarEnable">
          <div class="add-technology-left">
            <el-select class="add-technology-left-select" v-model="addMemberInfo.id" placeholder="选择成员">
              <el-option v-for="user in availUsers" :key="user.id" :label="user.name" :value="user.id" />
            </el-select>
            <el-select v-model="addMemberInfo.role.id" placeholder="部门身份">
              <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
            </el-select>
            <el-input v-model="addMemberInfo.annotation"></el-input>
          </div>
          <div class="add-technology-right">
            <el-button @click="addMember">添加</el-button>
            <el-button @click="toggleAddMemberInterface">取消</el-button>
          </div>
        </div>
      </section>
    </main>
  </div>
  <EditDepartmentDetailDialog ref="edit_dep_detail" @update="updateDepartment" />
  <!-- <Loading :isLoading="loading" /> -->
</template>

<script>
import { post } from '../../utils/common/api'
import MarkdownIt from 'markdown-it'
import EditDepartmentDetailDialog from '../../components/EditDepartmentDetailDialog.vue'
export default {
  data() {
    return {
      id: this.$route.params.id,
      profileData: {
        id: undefined,
        name: '',
        detail: '',
        members: [
          {
            id: undefined,
            name: '',
            annotation: '',
            role: {
              id: undefined,
              name: '',//人员的部门身份称谓
            }
          },
        ],
        projects: [
        ]
      },
      memberTableEditEndable: false,
      addMemberInfo: {
        id: undefined,
        role: {
          id: undefined,
        },
        annotation: ''
      },
      addMemberBarEnable: false,
      //部门身份的权限
      permissionsList: [
        {
          id: 1,
          name: '所有权限',
          detail: '	授予用户所有部门权限'
        },
        {
          id: 2,
          name: '修改部门信息',
          detail: '允许用户修改部门信息'
        },
        {
          id: 3,
          name: '	修改部门成员',
          detail: '允许用户增加、删除、修改部门成员'
        },
      ],
      //部门身份的列表
      roleList: [
        // {
        //   id: 1,
        //   name: '组长',
        //   permissions: [1]
        // },
        // {
        //   id: 2,
        //   name: '成员',
        //   permissions: []
        // }
      ],
      //工作室中的所有成员
      usersList: [],
      userSelect: undefined,

      /** 部门内部权限控制 */
      currentDepartmentRoleId: 23,
      currentDepartmentRolePerList: [],
      loading: false,
    }
  },
  computed: {
    availUsers() {
      //可以被添加的成员(需要筛选掉已经在部门中的成员)
      let memberIdList = [];
      this.profileData.members.forEach(member => {
        memberIdList.push(member.id)
      })
      return this.usersList.filter(user => !memberIdList.includes(user.id))
    },
    departmentDetail() {
      const md = new MarkdownIt()
      const result = md.render(this.profileData.detail)
      return result
    },
    DeletingDepartmentPermissions() {
      return this.usePermission.systemPermission.includes(1) || this.usePermission.systemPermission.includes(14)
    },
    ModifyingDepartmentInformation() {
      return this.currentDepartmentRolePerList.includes(1) || this.currentDepartmentRolePerList.includes(2)
    },
    ModifyDepartmentMembers() {
      return this.currentDepartmentRolePerList.includes(1) || this.currentDepartmentRolePerList.includes(3)
    },
  },
  methods: {
    async updateDepartment() {
      const res = await post('/department/profile', {
        id: this.id
      })
      this.profileData = res;
    },

    async getDepartmentRoleList() {
      const res = await post('/department/role/list', {
        id: this.id
      })
      this.roleList = res.list
    },

    async getAllUsersList() {
      const res = await post('/user/all', {})
      this.usersList = res.list
    },

    enterManagePage() {
      this.$router.push({
        path: `/department/edit/${this.id}`
      })
    },
    openDeleteDepartmentConfirmMessageBox() {
      var that = this
      ElMessageBox.prompt('请复述部门名字确认删除操作：', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }).then(function (res) {
        if (res.action == 'confirm') {
          if (res.value == that.profileData.name) {
            that.deleteDepartment()
          }
          else {
            ElNotification({
              title: '删除中断',
              message: `您输入的字符串与项目名称不符`,
              type: 'error',
              position: 'bottom-right',
            })
          }
        }
      }).catch(function () { })
    },
    deleteDepartment() {
      var that = this
      post('/department/delete', {
        id: that.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `成功将 No.${that.id} ${that.profileData.name} 从系统中移除`,
          type: 'success',
          position: 'bottom-right',
        })
        that.$router.push('/department')
      })
    },
    // },

    // 更新部门信息
    openEditDepDetailDialog() {
      this.$refs.edit_dep_detail.setDetail(this.id, this.profileData)
      this.$refs.edit_dep_detail.openDialog()
    },
    toggleAddMemberInterface() {
      this.addMemberBarEnable = !this.addMemberBarEnable
      this.addMemberInfo.id = undefined
      this.addMemberInfo.role.id = undefined
      this.addMemberInfo.annotation = ''
    },
    toggleMemberTableEdit() {
      this.memberTableEditEndable = !this.memberTableEditEndable
    },
    addMember() {
      var that = this
      post('/department/member/add', {
        did: that.id,
        member: that.addMemberInfo
      }).then(function (res) {
        ElNotification({
          title: '添加成功',
          message: `新增了 ${res.name} 成员`,
          type: 'success',
          position: 'bottom-right',
        })
        that.toggleAddMemberInterface()
        that.updateDepartment()
      })
    },

    /** 更新部门成员（部门身份，任职信息备注）信息 */
    toggleInMemberTableEdit(row) {
      var that = this
      if (row.inTableEdit == undefined) {
        row.inTableEdit = {
          annotation: row.annotation,
          role: {
            id: row.role.id
          }
        }
      }
      else {
        post('/department/member/update', {
          uid: row.id,
          did: that.id,
          mod: row.inTableEdit
        }).then(function (res) {
          Object.assign(row, res)
          ElNotification({
            title: '修改成功',
            message: `您刚刚修改了成员 ${res.name} 的相关信息`,
            type: 'success',
            position: 'bottom-right',
          })
        })
        row.inTableEdit = undefined
      }
    },

    //删除部门成员
    openDeleteUserConfirmMessageBox(user) {
      var that = this
      ElMessageBox.confirm(
        `将人员 ${user.name} (${user.id}) 从部门中移除？`,
        '警告',
        {
          confirmButtonText: '移除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(function () {
        that.deleteUser(user)
      })
    },

    deleteUser(user) {
      var that = this
      post('/department/member/delete', {
        uid: user.id,
        did: that.id
      }).then(function (res) {
        ElNotification({
          title: '删除成功',
          message: `成功将人员 ${user.name} (${user.id}) 从部门中移除`,
          type: 'success',
          position: 'bottom-right',
        })
        that.updateDepartment()
      })
    },

    async getData() {
      await this.getCurRoleId();
      await this.getCurRolePerList();
    },

    async getCurRoleId() {
      let that = this;
      try {
        const res = await post('/department/member/profile', {
          uid: that.usePermission.id,
          did: that.id
        });
        that.currentDepartmentRoleId = res.role.id;
      } catch (error) {
        console.error('Error in getCurRoleId:', error);
      }
    },

    async getCurRolePerList() {
      console.log(this.currentDepartmentRoleId);
      let that = this;
      try {
        const res = await post('/department/role/profile', {
          rid: that.currentDepartmentRoleId
        });
        that.currentDepartmentRolePerList = res.permissions;
      } catch (error) {
        console.error('Error in getCurRolePerList:', error);
      }
    },

    async loadData() {
      this.loading = true;
      await Promise.all([
        this.updateDepartment(),
        this.getAllUsersList(),
        this.getDepartmentRoleList()
      ])
      await this.getData()
      this.loading = false;
    }
  },
  mounted() {
    this.loadData()
  },
}
</script>

<style scoped>
.dep-page-head {
  margin-bottom: 40px;
}

header {
  height: 40px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 20px;
  margin-left: 10px;
}

.header-icon {
  cursor: pointer;
}

main {
  width: 100%;
}

.project-introduction {
  padding: 24px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  text-align: left;
  font-size: 15px;
  box-sizing: border-box;
}

.info-container {
  width: 75%;
  margin: 20px auto;
}

.descriptions-title {
  display: flex;
  align-items: center;
}

.descriptions-title-icon {
  margin-right: 7px;
}

.add-technology-box {
  display: flex;
  margin-top: 8px;
}

.add-technology-left {
  display: flex;
  flex-grow: 1;
  padding-right: 12px;
}

.add-technology-left>* {
  margin-right: 8px;
}

.add-technology-right {
  flex-grow: 0;
}
</style>